<template>
  <div class="page-detail">
    <div @back="() => this.$router.go(-1)">
      <div class="page-title">{{ $t('all.autotext432') }}</div>
      <section class="section">
        <div class="divider-title">
          <a-divider type="vertical" class="divider"/>
          <div>{{ detail.fileName }}</div>
          <div class="bg-shape" :class="dynamicClass()">{{ detail.status | enumValueByKey($const.SIGNING_STATUS) }}</div>
        </div>
        <a-descriptions bordered size="small">
          <a-descriptions-item :label="$t('all.autotext1407')"> {{ detail.signType === 1? $t('all.autotext440.1'): $t('all.autotext440.2') }} </a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext768')">
            {{ detail.signUserName }}
          </a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext901')"> {{ detail.account }} </a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext58')">
            {{ detail.createTime | moment() }}
          </a-descriptions-item>
        </a-descriptions>
      </section>

      <section class="section">
        <div class="divider-title">
          <a-divider type="vertical" class="divider"/>
          <div>{{ $t('all.autotext630') }}</div>
        </div>
        <div v-if="detail.signType === 2">
          <a-list item-layout="horizontal" :data-source="dataInfo.fileList" :locale="locale">
            <a-list-item slot="renderItem" slot-scope="record, index" class="list-item-wrapper">
              <div class="item-index">{{ index +1 }}</div>
              <a-list-item-meta description="" class="item-content">
                <a slot="title" @click="clickViewFile(record)">{{ record.fileName }}</a>
                <img slot="avatar" src="../../image/icon_pic.png"/>
              </a-list-item-meta>
              <div class="item-action">
                <a @click="deleteFile(record, index)" v-if="detail.status === 2"><img class="icon-warn" src="../../image/icon_delete.png" /></a>
                <a @click="clickViewImage(record, index)" v-else>{{ $t('all.autotext1477') }}</a>
              </div>
            </a-list-item>
          </a-list>
          <a-upload
            v-if="detail.status === 2"
            ref="import"
            name="file"
            :multiple="true"
            :before-upload="beforeUploadSite"
            :customRequest="handleUpload"
            :showUploadList="false"
          >
            <a-button style="margin-bottom: 10px;margin-top: 24px" :loading="uploading" type="primary">{{ $t('all.autotext67') }}</a-button>
          </a-upload>
        </div>

        <div v-if="detail.signType === 1">
          <a-list
            v-if="detail.status === 3"
            item-layout="horizontal"
            :data-source="dataInfo.fileList"
            :locale="locale"
          >
            <a-list-item slot="renderItem" slot-scope="record, index" class="list-item-wrapper">
              <div class="item-index">{{ index +1 }}</div>
              <a-list-item-meta description="" class="item-content">
                <a slot="title" @click="clickViewFile(record)">{{ record.fileName }}</a>
                <img slot="avatar" src="../../image/icon_pic.png"/>
              </a-list-item-meta>
              <div class="item-action">
                <a @click="downloadPDF(record, index)">{{ $t('all.autotext1477') }}</a>
              </div>
            </a-list-item>
          </a-list>
          <div v-else class="noteTitle">{{ $t('all.autotext838') }}</div>
        </div>
      </section>

      <section class="btn-wrapper">
        <div>
          <a-button
            v-if="detail.status === 1 && isNotPaperyContract()"
            type="primary"
            class="btn"
            @click="sign"
          >
            {{ $t('all.autotext945') }}
          </a-button>
          <a-button
            type="primary"
            class="btn"
            @click="submitData"
            v-if="detail.status === 2"
          >
            {{ $t('all.autotext218') }}
          </a-button>
          <a-button class="btn" @click="() => this.$router.go(-1)">{{ $t('all.autotext76') }}</a-button>
        </div>
      </section>
    </div>

    <UploadFile
      :uploadFileVisible="uploadFileVisible"
      :currentTarget="currentTarget"
      @closeUpload="closeUpload"
      ref="uploadFileRef"
    />

    <!-- 图片预览 -->
    <a-modal
      width="640px"
      :visible="imgVisible"
      :footer="null"
      @cancel="imgVisible = false"
    >
      <div class="image">
        <img :src="itemFileUrl | dealImageUrl">
      </div>
    </a-modal>
    <a-modal
      width="640px"
      :visible="signVisible"
      :footer="null"
      @cancel="signVisible = false"
      :title="$t('all.autotext213')"
    >
      <div class="signWrapper">
        <div>{{ $t('all.autotext1174') }}</div>
        <img class="qrcode-img" :src="qrcodeDataUrl" :alt="$t('all.autotext858')">
        <a-button @click="() => signVisible = false" type="primary">{{ $t('all.autotext892') }}</a-button>
      </div>
    </a-modal>
    <pdfPreview :visible="pdfVisible" :url="fileUrl" @handleCancel="pdfVisible = false" />
  </div>
</template>

<script>// eslint-disable-next-line no-unused-vars
import { getContractDetail, addFilePhoto, downloadContract } from '@/api/entrance/record'
import UploadFile from '../UploadFile'
import { uploadFile, getEsignUrl } from '@/api/common'
import Qrcode from '@/utils/qrcode'
import pdfPreview from '@/components/pdfPreview/index.vue'
import { exportZipcom } from '@/utils/util'

const opts = {
  errorCorrectionLevel: 'H',
  type: 'image/jpeg',
  quality: 1,
  margin: 1,
  color: {
    dark: '#FF9000',
    light: ''
  }
}
export default {
  name: 'record-detail-index',
  components: { UploadFile, pdfPreview },
  data () {
    return {
      detail: {},
      dataInfo: {
        fileList: []
      },
      uploading: false,
      locale: {
        emptyText: this.$t('all.autotext341')
      },
      signVisible: false,
      qrcodeDataUrl: '',
      fileUrl: '',
      pdfVisible: false,



      paymentDetails: {},
      status: '',
      originDetail: {},
      uploadFileVisible: false,
      currentTarget: {},
      personalTaxObj: {},
      paymentObj: {},
      imgVisible: false,
      itemFileUrl: ''
    }
  },
  async created () {
    this.fetchRecordDetail()
  },
  methods: {
    // 下载PDF
    async downloadPDF () {
      const res = await downloadContract({ conId: this.detail.id })
      exportZipcom(this.detail.fileName.split('.')[0], res)
    },
    // 预览pdf或下载其他格式文件
    clickViewImage (item) {
      const fileUrl = this.$options.filters.dealImageUrl(item.fileUrl)
      window.open(fileUrl, '_blank')
    },
    // 点击删除上传的文件
    deleteFile (row, index) {
      this.dataInfo.fileList.splice(index, 1)
      this.$forceUpdate()
    },
    beforeUploadSite (file) {
      const formatImg = /((gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i
      const formatPdf = /(pdf)$/i
      // const formatWord = /((doc|docx|wps))$/i
      const formatWord = /((msword|vnd.openxmlformats-officedocument.wordprocessingml.document|kswps))$/i
      if (formatImg.test(file.type)) {
        return true
      } else if (formatPdf.test(file.type)) {
        return true
      } else if (formatWord.test(file.type)) {
        return true
      } else {
        this.$message.error(this.$t('all.autotext293'))
        return false
      }
    },
    // 修改上传
    handleUpload ({ file }) {
      // 校验格式
      const info = {}
      this.uploading = true
      // 将上传的文件进行展示
      info.fileName = file.name
      info.uniqueId = Math.random().toString().substr(2, 10)
      this.$forceUpdate()
      const request = uploadFile
      const params = new FormData()
      params.append('file', file)
      return request(params, function (e) {
        if (e.lengthComputable) {
          let rate = e.loaded / e.total // 已上传的比例
          console.log('rate', rate)
        }
      }).then(res => {
        info.fileUrl = res
        info.afterFileUrl = res
        if (this.dataInfo.fileList.length) {
          this.dataInfo.fileList.push(info)
        } else {
          this.dataInfo.fileList = []
          this.dataInfo.fileList.push(info)
        }
        this.$forceUpdate()
      }).catch(() => {
      }).finally(() => {
        this.uploading = false
      })
    },

    // 文件预览
    clickViewFile (record) {
      const formatImg = /(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i
      if (formatImg.test(record.fileUrl)) {
        this.itemFileUrl = record.fileUrl
        this.imgVisible = true
      } else {
        // 打开空白页 展示文件
        const fileUrl = this.$options.filters.dealImageUrl(record.fileUrl)
        window.open(fileUrl, '_blank')
      }
    },
    sign () {
      this.signVisible = true
    },
    async submitData () {
      let list = this.dataInfo.fileList
      let jsonList = []
      list.map(({ fileUrl }) => {
        jsonList.push(fileUrl)
      })
      let params = {
        conId: this.$route.query.id,
        url: jsonList.join()
      }
      await addFilePhoto(params).then(res => {
      })
      this.$message.success(this.$t('all.autotext1401'))
      this.$router.go(-1)
    },
    addFiles (record) {
      this.uploadFileVisible = true
      this.currentTarget = record
      this.$refs.uploadFileRef.copyData(record)
      this.$refs.uploadFileRef.resetData()
    },
    // 关闭文件上传
    closeUpload (info) {
      const target = this.originDetail.detailList.find(item => item.id === info.id)
      if (target) {
        target.fileList = info.fileList
        if (target.fileList.length) {
          target.fileUrl = target.fileList.map(item => item.fileUrl).toString()
        } else {
          target.fileUrl = ''
        }
      }
      this.uploadFileVisible = false
      this.$forceUpdate()
    },
    dynamicClass () {
      const status = this.detail.status

      let className = ''
      switch (status) {
        case 1:
          className = 'orange-shape' // 待提交 TODO UI颜色未指定
          break
        case 2:
          className = 'orange-shape' // 待补充
          break
        case 3:
          className = 'pink-shape' // 审核中
          break
        case 4:
          className = 'pink-shape' // 审核中
          break
        default:
          className = 'orange-shape'
          break
      }
      return className
    },
    isNotPaperyContract () {
      return this.detail.signType && this.detail.signType !== 2
    },
    fetchRecordDetail () {
      const datailsId = this.$route.query.id
      getContractDetail({ id: Number.parseFloat(datailsId) }).then((res) => {
        this.detail = res
        let filesList = []
        let files = res.fileUrl?.split(',')
        files && files.map((item) => {
          filesList.push({
            fileUrl: item,
            fileName: res.fileName
          })
        })
        this.dataInfo.fileList = filesList
        if (this.isNotPaperyContract()) {
          this.fetchEsignUrl(res)
        }
      })
    },
    async fetchEsignUrl ({ flowId, phone }) {
      const url = await getEsignUrl({ flowId, phone })
      // const dataUrl = await Qrcode.generateByText(`https://testepayment.primelifescience.com.cn/uniapp?flowId=${flowId}&phone=${phone}`, opts)
      const dataUrl = await Qrcode.generateByText(url, opts)
      this.qrcodeDataUrl = dataUrl
    }
  }
}
</script>

<style scoped lang="less">
  .ant-descriptions-bordered .ant-descriptions-item-label {
    background: rgba(241, 245, 248, 0.6) !important;
  }
  .orange-shape {
    background: #FFF9DC;
    color: #E88F1A;
  }
  .pink-shape {
    background: #FFEEE9;
    color: #E95A34;
  }
  .green-shape {
    background: #2BDDA8;
    color: #fff;
  }
  .blue-shape {
    background: #0079FF;
    color: #fff;
  }
  .dark-shape {
    background: #0F121B;
    color: #fff;
  }
  .signWrapper {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .qrcode-img {
      color: red;
      width: 200px;
      height: 200px;
      margin-top: 24px;
      margin-bottom: 32px;
    }
  }
  .noteTitle {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    color: #999;
    line-height: 22px;
    margin-top: 24px;
  }
  .list-item-wrapper {
    width: 669px;
    height: 66px;
    padding: 9px 8px;
    border: 1px solid #D9D9D9;
    border-radius: 2px;

    .ant-list-item-meta-avatar {
      margin-left: 8px;
      margin-right: 8px;
    }
    .item-index {
      width: 66px;
      height: 66px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-right: 1px solid #D9D9D9;
    }
    .item-action {
      width: 100px;
      height: 66px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-left: 1px solid #D9D9D9;
    }
    .ant-list-item-meta-content {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      height: 48px;
    }
  }
  .ant-list-split .ant-list-item:last-child {
    border-bottom: 1px solid #D9D9D9;
  }
  .page-detail {
    min-height: calc(100vh - 274px);
    overflow: auto;
    display: flex;
    flex-direction: column;
    background: #fff;
    padding: 32px 25px 12px 20px;

    .page-title {
      font-size: 18px;
      font-weight: bold;
      color: #232323;
      margin-bottom: 24px;
    }

    .section {
      margin-bottom: 32px;

      .divider-title {
        display: flex;
        flex-direction: row;
        font-size: 16px;
        font-weight: 400;
        color: #0F121B;
        align-items: center;
        margin-bottom: 24px;

        .divider {
          height: 20px;
          width: 4px;
          background: #43D8D2;
          margin-left: 0px;
        }

        .bg-shape {
          width: 64px;
          height: 26px;
          //background: #2BDDA8;
          display: flex;
          justify-content: center;
          align-items: center;
          border-top-left-radius: 13px;
          border-top-right-radius: 13px;
          border-bottom-right-radius: 13px;
          margin-left: 24px;

          font-size: 13px;
          font-weight: 400;
          //color: #fff;
          line-height: 18px;
        }
      }

      .a-class {
        color: #0079FF;
        font-size: 14px;
        line-height: 22px;
      }

      .btnWrapper {
        display: flex;
        align-items: center;
        justify-content: flex-start;
      }

      .qr-code {
        width: 21px;
        height: 21px;
        margin-right: 18px;
      }
      .qrcode-a {
        font-size: 12px;
        color: #0079FF;
        line-height: 16px;
      }
    }

    .btn-wrapper {
      margin-top: 270px;
      display: flex;
      flex:1;
      align-items: flex-end;
      .btn {
        width: 120px;
        height: 36px;
        margin-right: 24px;
      }
    }
  }
</style>
